#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户管理API路由
"""

from flask import Blueprint, request, jsonify
from models.user import User
from models.order import Order
from models.recharge import Recharge
from database import db
from utils.decorators import admin_required
from datetime import datetime
from sqlalchemy import or_, and_

user_bp = Blueprint('user', __name__)

@user_bp.route('/', methods=['GET'])
@admin_required
def get_users(admin):
    """获取用户列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        status = request.args.get('status', '', type=str)
        is_member = request.args.get('is_member', '', type=str)
        
        # 构建查询
        query = User.query
        
        if search:
            query = query.filter(or_(
                User.nickname.like(f'%{search}%'),
                User.phone.like(f'%{search}%'),
                User.openid.like(f'%{search}%')
            ))
        
        if status:
            query = query.filter(User.status == int(status))
        
        if is_member:
            query = query.filter(User.is_member == (is_member.lower() == 'true'))
        
        # 分页查询
        pagination = query.order_by(User.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        users = pagination.items
        
        return jsonify({
            'success': True,
            'data': {
                'users': [user.to_dict() for user in users],
                'pagination': {
                    'page': page,
                    'pages': pagination.pages,
                    'per_page': per_page,
                    'total': pagination.total,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取用户列表失败: {str(e)}'}), 500

@user_bp.route('/<int:user_id>', methods=['GET'])
@admin_required
def get_user(admin, user_id):
    """获取用户详情"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'}), 404
        
        # 获取用户统计信息
        order_count = Order.query.filter_by(user_id=user_id).count()
        recharge_count = Recharge.query.filter_by(user_id=user_id).count()
        
        recent_orders = Order.query.filter_by(user_id=user_id).order_by(
            Order.created_at.desc()
        ).limit(5).all()
        
        recent_recharges = Recharge.query.filter_by(user_id=user_id).order_by(
            Recharge.created_at.desc()
        ).limit(5).all()
        
        user_data = user.to_dict()
        user_data['statistics'] = {
            'order_count': order_count,
            'recharge_count': recharge_count,
            'recent_orders': [order.to_dict() for order in recent_orders],
            'recent_recharges': [recharge.to_dict() for recharge in recent_recharges]
        }
        
        return jsonify({
            'success': True,
            'data': user_data
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取用户详情失败: {str(e)}'}), 500

@user_bp.route('/<int:user_id>', methods=['PUT'])
@admin_required
def update_user(admin, user_id):
    """更新用户信息"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'}), 404
        
        data = request.get_json()
        
        # 更新用户信息
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'phone' in data:
            user.phone = data['phone']
        if 'status' in data:
            user.status = data['status']
        if 'is_member' in data:
            user.is_member = data['is_member']
        if 'member_level' in data:
            user.member_level = data['member_level']
        if 'member_expire_date' in data:
            if data['member_expire_date']:
                user.member_expire_date = datetime.fromisoformat(data['member_expire_date'])
            else:
                user.member_expire_date = None
        if 'balance' in data:
            user.balance = data['balance']
        
        user.updated_at = datetime.now()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '用户信息更新成功',
            'data': user.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'更新用户信息失败: {str(e)}'}), 500

@user_bp.route('/<int:user_id>/balance', methods=['PUT'])
@admin_required
def adjust_balance(admin, user_id):
    """调整用户余额"""
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'}), 404
        
        data = request.get_json()
        amount = data.get('amount', 0)
        operation = data.get('operation', 'add')  # add增加, subtract减少, set设置
        remark = data.get('remark', '')
        
        if not amount and operation != 'set':
            return jsonify({'success': False, 'message': '金额不能为空'}), 400
        
        old_balance = float(user.balance)
        
        if operation == 'add':
            user.balance += amount
        elif operation == 'subtract':
            if user.balance < amount:
                return jsonify({'success': False, 'message': '余额不足'}), 400
            user.balance -= amount
        elif operation == 'set':
            user.balance = amount
        else:
            return jsonify({'success': False, 'message': '无效的操作类型'}), 400
        
        user.updated_at = datetime.now()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '余额调整成功',
            'data': {
                'old_balance': old_balance,
                'new_balance': float(user.balance),
                'amount': amount,
                'operation': operation
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'调整余额失败: {str(e)}'}), 500

@user_bp.route('/statistics', methods=['GET'])
@admin_required
def get_user_statistics(admin):
    """获取用户统计信息"""
    try:
        total_users = User.query.count()
        active_users = User.query.filter(User.status == 1).count()
        member_users = User.query.filter(User.is_member == True).count()
        
        # 最近7天新增用户
        from datetime import timedelta
        seven_days_ago = datetime.now() - timedelta(days=7)
        new_users_week = User.query.filter(User.created_at >= seven_days_ago).count()
        
        # 用户余额统计
        total_balance = db.session.query(db.func.sum(User.balance)).scalar() or 0
        
        return jsonify({
            'success': True,
            'data': {
                'total_users': total_users,
                'active_users': active_users,
                'member_users': member_users,
                'new_users_week': new_users_week,
                'total_balance': float(total_balance),
                'member_rate': round(member_users / total_users * 100, 2) if total_users > 0 else 0
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取统计信息失败: {str(e)}'}), 500